package com.hui.qiniucloud.controller;

import com.hui.qiniucloud.dto.*;
import com.hui.qiniucloud.entity.AppHttpCodeEnum;
import com.hui.qiniucloud.entity.Result;
import com.hui.qiniucloud.entity.User;
import com.hui.qiniucloud.service.IChatService;
import com.hui.qiniucloud.utils.AppThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import java.util.List;

/**
 * 聊天控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
@Tag(name = "聊天管理", description = "聊天消息发送、历史记录管理等接口")
public class ChatController {

    @Autowired
    private IChatService chatService;

    /**
     * 发送聊天消息
     */
    @Operation(summary = "发送聊天消息",
               description = "发送消息给AI，支持新建会话和继续对话，支持角色扮演",
               requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                   description = "聊天消息请求",
                   content = @Content(
                       mediaType = "application/json",
                       examples = @io.swagger.v3.oas.annotations.media.ExampleObject(
                           name = "发送消息示例",
                           summary = "发送聊天消息请求示例",
                           value = """
                               {
                                 "content": "你好，请介绍一下你自己",
                                 "sessionId": 1,
                                 "characterId": "harry_potter",
                                 "sessionTitle": "关于魔法的讨论"
                               }
                               """
                       )
                   )
               ))
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "消息发送成功"),
        @ApiResponse(responseCode = "400", description = "参数错误"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PostMapping("/message")
    public Result<ChatMessageResponse> sendMessage(@Valid @RequestBody ChatMessageRequest request) {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            ChatMessageResponse response = chatService.sendMessage(user.getId(), request);
            return Result.success(response);
        } catch (Exception e) {
            log.error("发送聊天消息失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取用户的聊天会话列表
     */
    @Operation(summary = "获取聊天会话列表", description = "获取当前用户的所有聊天会话")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/sessions")
    public Result<List<ChatSessionResponse>> getUserSessions() {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            List<ChatSessionResponse> sessions = chatService.getUserSessions(user.getId());
            return Result.success(sessions);
        } catch (Exception e) {
            log.error("获取会话列表失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据角色ID获取聊天会话列表
     */
    @Operation(summary = "根据角色获取会话列表", description = "获取与指定角色的聊天会话")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/sessions/character/{characterId}")
    public Result<List<ChatSessionResponse>> getUserSessionsByCharacter(
            @Parameter(description = "角色ID") @PathVariable String characterId) {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            List<ChatSessionResponse> sessions = chatService.getUserSessionsByCharacter(user.getId(), characterId);
            return Result.success(sessions);
        } catch (Exception e) {
            log.error("根据角色获取会话列表失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 获取聊天历史记录
     */
    @Operation(summary = "获取聊天历史记录", description = "获取指定会话的完整聊天记录")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "404", description = "会话不存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/history/{sessionId}")
    public Result<ChatHistoryResponse> getChatHistory(
            @Parameter(description = "会话ID") @PathVariable Long sessionId) {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            ChatHistoryResponse history = chatService.getChatHistory(user.getId(), sessionId);
            return Result.success(history);
        } catch (Exception e) {
            log.error("获取聊天历史失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 删除聊天会话
     */
    @Operation(summary = "删除聊天会话", description = "删除指定的聊天会话及其所有消息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "404", description = "会话不存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @DeleteMapping("/sessions/{sessionId}")
    public Result<String> deleteSession(
            @Parameter(description = "会话ID") @PathVariable Long sessionId) {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            chatService.deleteSession(user.getId(), sessionId);
            return Result.success("会话删除成功");
        } catch (Exception e) {
            log.error("删除会话失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 更新会话标题
     */
    @Operation(summary = "更新会话标题", description = "修改聊天会话的标题")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "404", description = "会话不存在"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PutMapping("/sessions/{sessionId}/title")
    public Result<String> updateSessionTitle(
            @Parameter(description = "会话ID") @PathVariable Long sessionId,
            @Parameter(description = "新标题") @RequestParam @NotBlank @Size(max = 200) String title) {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            chatService.updateSessionTitle(user.getId(), sessionId, title);
            return Result.success("标题更新成功");
        } catch (Exception e) {
            log.error("更新会话标题失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 搜索聊天会话
     */
    @Operation(summary = "搜索聊天会话", description = "根据关键词搜索聊天会话")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "搜索成功"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/sessions/search")
    public Result<List<ChatSessionResponse>> searchSessions(
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            List<ChatSessionResponse> sessions = chatService.searchSessions(user.getId(), keyword);
            return Result.success(sessions);
        } catch (Exception e) {
            log.error("搜索会话失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 清空所有聊天记录
     */
    @Operation(summary = "清空所有聊天记录", description = "删除当前用户的所有聊天会话和消息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "清空成功"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @DeleteMapping("/sessions/clear")
    public Result<String> clearAllSessions() {
        User user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return Result.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        try {
            chatService.clearAllSessions(user.getId());
            return Result.success("所有聊天记录已清空");
        } catch (Exception e) {
            log.error("清空聊天记录失败: {}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }
}